package com.jarvis.pzz.modules.login;


import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jarvis.pzz.R;
import com.jarvis.pzz.common.BaseActivity;
import com.jarvis.pzz.common.ResponseData;
import com.jarvis.pzz.models.LoginModel;
import com.jarvis.pzz.models.LoginRequestModel;
import com.jarvis.pzz.seervers.RequestService;
import com.jarvis.pzz.util.DateUtil;
import com.jarvis.pzz.util.JCountDownTimer;
import com.jarvis.pzz.util.SharePreferenceKey;
import com.jarvis.pzz.util.SharePreferenceUtils;
import com.jarvis.pzz.util.Util;
import com.jarvis.pzz.util.net.RequestApi;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LoginActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.rel_send)
    RelativeLayout rel_send;
    @BindView(R.id.rel_back)
    RelativeLayout rel_back;
    @BindView(R.id.tv_send)
    TextView tv_send;
    @BindView(R.id.ed_phone)
    EditText ed_phone;
    @BindView(R.id.ed_idenfy)
    EditText ed_idenfy;

    private RequestService service;
    private String phone;
    private String idenfy;
    private MyCountDown countDown;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData() {
        countDown = new MyCountDown(60000, 1000);
    }

    @Override
    public void initView() {
        setListener();
        service = RequestApi.create(RequestService.class);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (countDown != null && countDown.isRunning()) {
            countDown.reStart();

        }
    }

    @Override
    protected void onStop() {

        if (countDown != null && countDown.isRunning()) {
            countDown.pause();

        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (countDown != null) {
            countDown.cancel();
        }
        super.onDestroy();
    }

    private void setListener() {
        tv_login.setOnClickListener(this);
        rel_send.setOnClickListener(this);
        rel_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_back:
                finish();
                break;
            case R.id.tv_login:
                //startActivity(MainCounselorActivity.class);
                checkLogin();
                break;
            case R.id.rel_send:
                checkMobile();
                break;
        }
    }

    private void checkMobile() {
        phone = ed_phone.getText().toString();
        idenfy = ed_idenfy.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showTextToast("电话号码不能为空");
        } else {
            getIdenfy();
        }
    }

    public void checkLogin() {
        phone = ed_phone.getText().toString();
        idenfy = ed_idenfy.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showTextToast("电话号码不能为空");
        } else if (TextUtils.isEmpty(idenfy)) {
            showTextToast("验证号码不能为空");
        }else {
            doLogin();
        }
    }

    public void getIdenfy() {
        showDialog("loading");
        String currentTime = DateUtil.getInstance().getCurrentDate();
        String phone_4 = phone.substring(phone.length() - 4, phone.length());
        String SecretToken = Util.getSecretToken(currentTime, phone_4);
        Call<ResponseData> call = service.sendMessage(phone, currentTime, SecretToken);
        call.enqueue(new Callback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
                disMiss();
                if (response.body() != null) {
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        countDown.start();
                        rel_send.setEnabled(false);
                        showTextToast("验证码已发送，请注意查收");
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }

            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                disMiss();
                showTextToast(RequestApi.detailError(t));
            }
        });
    }

    public void doLogin() {
        showDialog("loading");
        Call<ResponseData<LoginModel>> call = service.login(phone, idenfy);
        call.enqueue(new Callback<ResponseData<LoginModel>>() {
            @Override
            public void onResponse(Call<ResponseData<LoginModel>> call, Response<ResponseData<LoginModel>> response) {
                disMiss();
                if (response.body() != null) {
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        MobclickAgent.onProfileSignIn(phone);
                        LoginModel loginModel = response.body().getData();
                        SharePreferenceUtils.putObject(SharePreferenceKey.LOGIN_MODEL, loginModel);
                        SharePreferenceUtils.putString(SharePreferenceKey.USER_ID, loginModel.getUserInfo().getUserId());
                        finish();
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }

            }

            @Override
            public void onFailure(Call<ResponseData<LoginModel>> call, Throwable t) {
                disMiss();
                showTextToast(RequestApi.detailError(t));
            }
        });
    }

    public class MyCountDown extends JCountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv_send.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            tv_send.setText("发送验证码");
            rel_send.setEnabled(true);
        }
    }
}
